const {
  sleepTime
} = require("../../utils/util");
const util = require("../../utils/util");
var crcUtils = require("../../utils/crc.js");
const app = getApp();
const ems_service = app.emsBlueData.ems_server_uuid;
const ems_character = app.emsBlueData.ems_character_uuid;
var utils = require("../../utils/util.js");
const application = require("./application");
var linkedManage = require("./link");

var isVisable = true;
const delayTime = 1; //延迟时长
const defaultByteLength = 20; //默认大小
var last_receiver_data_time = -1; //上次接收报文时间
const package_time_out = 2000; //报文间隔
var projectfile = require('../../components/pb/projectfile');
const sendFileSize = 800; //文件下发一条报文大小
var ackFileCount = 0; //应对收到文件的大小
var errorCode = 0xE1; //打开文件码值
//训练计时器
var trainTimer;
// 训练持续时间
var trainLastTime = 0;
// link time
var linkLastTime = 0;

const totalTrainTime = 100 * 60 * 60; //定时器时长
const trainTimerName = "trainTimer";
const linkTimerName = "trainTimer";

var Timer = require("../../utils/wxTimer.js");
const link = require("./link");
const {
  sendFileData
} = require("./application");
const blue = require("./blue");
var todo_send_blue_data = []; //待发送报文数据

//link 计时器
var linkTimer;
const iosSupportMtu=180;//苹果支持的mtu
const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: true
})
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chs: [],
    project_name: '请选择程序文件',
    config_name: '请选择配置文件',
    isShow_01: false,
    log_data: '',
    band_log_data: '',
    calc_count: 0,
    isClick: false,
    isClickFrameWork: false,
    receiverEmsData: [], //应用层数据内容
    receiverCommandEmsData: [], //命令层数据内容
    receiverEmsCount: 0,
    curretSelectMenu: 0,
    mtuValue: 1, //mtu 默认大小
    supportMtu: 500, //手机支持mtu大小
    slideSupportMtu:25,//mtu slide
    isHideMaintain: true, //是否隐藏维护模式
    listData_01: [
        "19200",
        "38400",
        "57600",
        "115200",
        "250000",
        "500000",
    ],
    picker_01_data: 250000,
    picker_01_index: 4,
    //频率
    band_array: [0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5
    ],
    items: [

      {
        name: "更新程序",
        value: "1",
        operatorValue: application.down_file_pre_update_project,
        checked:false,
        disable:true
      },
      // {
      //   name: "更新配置",
      //   value: "2"
      // },
      // {
      //   name: "读取配置",
      //   value: "3",
      // },
      {
        name: "读取信息",
        value: "4",
        operatorValue: application.down_file_pre_red_info,
        checked:false,
        disable:true
      },
      {
        name: "运行程序",
        value: "5",
        operatorValue: application.down_file_pre_run,
        checked:false,
        disable:true
      },
      // {
      //   name: "工作模式",
      //   value: "6"
      // },
      // {
      //   name: "打开缓冲区",
      //   value: "7"
      // },
      // {
      //   name: "擦除缓冲区",
      //   value: "8"
      // },
      // {
      //   name: "下发文件",
      //   value: "9"
      // },
      // {
      //   name: "关闭缓冲区",
      //   value: "10"
      // },
      // {
      //   name: "下发参数",
      //   value: "11"
      // },
      // {
      //   name: "开始执行",
      //   value: "12"
      // },
      // {
      //   name: "链路重置",
      //   value: "13"
      // },
      // {
      //   name: "工作模式查询",
      //   value: "14"
      // },
      {
        name: "连续操作",
        value: "0",
        operatorValue: 0,
        checked:false,
        disable:true
      },
    ],
    project_data: [], //选择的程序内容
    sendFileOffset: 0, //文件下发下标
    project_data_size: 0, //文件大小
    wxTimerList: {},
    isResetLinkSuccess: false, //链路层是否初始化成功
    isShowSendFileProgress: false, //是否显示进度条
    isNeedClearBuffer: false, //是否需要擦除缓冲区
    sendFilePecenter: 0, //文件下发进度
    isShowUpDateProject: false, //是否更新程序
    workModel: 0, //默认boot
    framework_name: '', //framework 名称
    isNeedSendParame: false, //是否需要下发参数
    isShowBandActionDialog:false,//是否显示板卡操作进度条
    bandActionProgress:0,//板卡操作的进度条
    bandStatus:'准备中',//板卡操作状态
    bandStatusError:"",//板卡错误信息
    intervalValue:1000,//连续执行停顿时间
    isShowConfigMtu:true,//是否可配置mtu
    array: ['美国', '中国', '巴西', '日本'],
    isExcuting:false,//是否是执行中
    intervalValueShow:1,//显示间隔时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    this.setData({
      deviceId: options.deviceId
    });
    if(app.globalData.sysinfo.platform=='ios'){
      this.setData({
        isShowConfigMtu:false
      })
      that.configBlueMtu(iosSupportMtu)
    }else{
      wx.onBLEMTUChange(function (res) {
        console.log('bluetooth mtu is', res.mtu)
      })
      that.setBlueMtu(20)
    }
    setTimeout(function () {
      linkedManage.setApplicationWatch(function handlerReceiverData(params) {
        console.log("msg watch receiver:", params)
        if (params.length <= 1) {
          //处理非数据内容
          if (params[0] === 0) {
            console.log("接收到链路层 重置成功，开始定时链路数据发送")
            that.startLinkTimer()
            that.setData({
              isResetLinkSuccess: true
            })
            that.show_log("链路重置成功")
            that.queryWorkModel(1);
          } else {
            that.setData({
              isResetLinkSuccess: false
            })
          }
          console.log("链路和配置成功", linkedManage.LinkCode.properties[params].name)
        } else {
          //应用层业务
          let appdata = params.concat()
          let result = application.handleAppData(appdata)
          that.handleAppResult(result)
        }
      });
      linkedManage.startBlueConnect(that.data.deviceId);
    }, 200);
    this.startTrainTimer(totalTrainTime)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
    isVisable = true;
    app.keepMainScreenOn();
  },

  //设置title
  setTitle: function (title) {
    wx.setNavigationBarTitle({
      title: title
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    isVisable = false;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    isVisable = false;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  //选择本地文件
  selectFile(e, selectResult) {
    const that = this
    var selectId = e.currentTarget.id;
    console.log(selectId)
    wx.chooseMessageFile({ // 使用微信的方法进入聊天界面选择你之前接受过的文件
      count: 1, // 最多可以选择的文件个数，可以 0～100
      type: 'file', // 所选的文件的类型，其它属性可以看官方文档
      success(res) {
        const fs = wx.getFileSystemManager() // 再调用一下微信的文件管理器，里面很多方法，但这里的需求是获取文件内容，所以我这里用readFile方法
        fs.readFile({
          filePath: `${res.tempFiles[0].path}`, // 这里的路径可以在上一步打印一下，然后填写即可
          encoding: 'hex',
          success(fsres) {
            // console.log(fsres.data)
            that.data.project_data = fsres.data
            that.data.project_data_size = fsres.data.length / 2 + 100
            if (selectId == 'project_id') {
              that.setData({
                project_name: res.tempFiles[0].name
              })
            } else {
              that.setData({
                framework_name: res.tempFiles[0].name
              })
            }
            if (null != selectResult) {
              selectResult(e) 
            }
            that.data.items[0].checked=true
            that.setData({
              items:that.data.items
            })
          },
          fail(err) {
            console.log(err)
          }
        })
      },
      fail(error) {
        console.log("选择文件失败", error)
      }
    })
  },
  /**
   * 波特率 picker 组件选择 确定操作
   * @param {*} e
   */
  sureCallBack_01(e) {
    console.log(e);
    let that = this;
    this.setData({
      picker_01_index: e.detail.value
    });
  },
  /**
   * 波特率picker 组件取消操作
   */
  cancleCallBack_01() {
    this.setData({
      isShow_01: false
    });
  },
  /**
   * 波特率选择
   */
  selectBand() {
    this.setData({
      isShow_01: true
    });
  },

  /**
   * 日志显示
   * @param {日志信息} data 
   */
  show_log(data) {
    let that = this
    let time=utils.formatTime(new Date())+": "
    this.setData({
      log_data: time+data + "\n"+that.data.log_data
    });
  },
  /**
   * 板卡信息显示
   */
  show_band_log(data) {
    let that = this
    let time=utils.formatTime(new Date())+": "
    this.setData({
      band_log_data: '<p>'+time+data+'</p>'+ that.data.band_log_data
    });
  },
  /**
   * 清屏操作
   */
  clear_log() {
    this.setData({
      log_data: '',
      band_log_data: '',
      bandStatusError:''
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  touchStartEms: function () {
    var that = this;
    that.setData({
      isClick: true
    });
  },
  touchEndEms: function () {
    var that = this;
    if (!that.data.isResetLinkSuccess) {
      wx.showToast({
        title: '设备初始化失败',
      })
    }
    that.setData({
      isClick: false
    });
    if(that.data.items[0].checked){
        //更新程序操作
        that.showSendFileDialog();
    }else if(that.data.curretSelectMenu>0){
      that.controlBandDialog(true)
      that.changeCalcuCount(0)
      if (that.data.workModel == 0) {
        that.setData({
          isNeedSendParame:true
        })
        //需要切换到工作模式
        that.switchWorkModel();
      } else {
        that.doDownLoadCommand(that.data.curretSelectMenu);
      }
    }
    // this.doSelectMenu(this.data.curretSelectMenu)
    // this.startLinkConnected();
    // this.analysisProtobuf()
  },
  /************************************************设备指令交互以下*********************************************************/
  //开启链路连接
  startLinkConnected: function () {
    linkedManage.sendRestLinkPackage();
  },
  //查询或者切换 model=1 查询 model=2 切换
  queryWorkModel: function (model) {
    console.log("工作模式操作", model)
    let workModel = application.doWorkModel(model);
    console.log("工作模式操作 报文" + utils.byteArrayToHex(workModel))
    let workModelData = linkedManage.sendApplicationData(0, workModel)
    linkedManage.sendBlueData(workModelData)
    let modelName = model === 1 ? "查询模式" : "切换到工作模式"
    this.show_log("发送模式状态:" + modelName)
  },
  sendAppCommSendDate: function (sendata) {
    let workModelData = linkedManage.sendApplicationData(0, sendata)
    console.log("...." + utils.byteArrayToHex(workModelData))
    linkedManage.sendBlueDataQueue(false, workModelData)
  },
  // 解析crc
  parseCrc: function (e) {
    if (!e) return null;
    let crc = crcUtils.ToCRC16(e, false);
    console.log("crc 计算+" + crc);
    return crc;
  },
  getWxMTU: function () {
    let that = this;
    try {
      console.log("getMaxBLEMTU",mtu)
      wx.getBLEMTU({
        deviceId: '',
        writeType: 'write',
        success(res) {
          that.setData({
            supportMtu: res.mtu - 3
          });
          blue.configMTU(that.data.supportMtu)
          console.log("MTU:" + res.mtu)
          that.show_log("MTU大小：" + res.mtu)
        }
      })
    } catch (error) {
      console.log("mtu error")
    }

  },
  radioChange: function (e) {
    var items = this.data.items;
    let tpm;
    for (var i = 0; i < items.length; ++i) {
      items[i].checked = items[i].value == e.detail.value;
      if (items[i].checked) {
        tpm = items[i].value;
      }
    }
    console.log(items);
    this.setData({
      items: items,
      curretSelectMenu: tpm
    });
    // this.doSelectMenu(tpm)
  },
  checkBoxChange: function (e) {
    let that = this;
    let items = this.data.items;
    const values = e.detail.value;
    let tpm = 0;
    for (let i = 0; i < items.length; ++i) {
      items[i].checked = false
      for (let j = 0; j < values.length; j++)
        if (items[i].value == values[j]) {
          if (items[i].value == items[0].value) {
            if (that.data.project_data.length < 1) {
              wx.showToast({
                title: '请先选择程序文件',
              })
              break;
            }
          }
          items[i].checked = true
          tpm += items[i].operatorValue
          break;
        }
    }
    console.log(items);
    console.log('select value:' + tpm);
    this.setData({
      items: items,
      curretSelectMenu: tpm
    });
  },
  //菜单选项处理
  doSelectMenu: function (index) {
    switch (parseInt(index)) {
      case 1:
        //更新程序
        let readConfigDataUpdateProject = application.readConfig(this.data.picker_01_index, application.down_file_pre_update_project)
        console.log("readConfigDataUpdateProject....before.." + utils.byteArrayToHex(readConfigDataUpdateProject))
        this.sendAppCommSendDate(readConfigDataUpdateProject);
        break;
      case 2:
        //更新配置
        let readConfigDataUpdateConfig = application.readConfig(this.data.picker_01_index, application.down_file_pre_update_config)
        console.log("readConfig....before.." + utils.byteArrayToHex(readConfigDataUpdateConfig))
        this.sendAppCommSendDate(readConfigDataUpdateConfig);
        break;
      case 3:
        //读取配置
        let readConfigData1 = application.readConfig(this.data.picker_01_index, application.down_file_pre_read_config)
        console.log("readConfigData1....before.." + utils.byteArrayToHex(readConfigData1))
        this.sendAppCommSendDate(readConfigData1);
        break;
      case 4:
        //读取信息
        let senReadInfodata = application.readConfig(this.data.picker_01_index, application.down_file_pre_red_info)
        console.log("readDeviceInfo....before.." + utils.byteArrayToHex(senReadInfodata))
        this.sendAppCommSendDate(senReadInfodata);
        break;
      case 5:
        //运行程序
        let readConfigData = application.readConfig(this.data.picker_01_index, application.down_file_pre_run)
        console.log("readConfig....before.." + utils.byteArrayToHex(readConfigData))
        this.sendAppCommSendDate(readConfigData);
        break;
      case 6:
        //切换到工作模式
        this.queryWorkModel(2);
        console.log("time1", Date.now())
        utils.sleepTime(2000)
        console.log("time2", Date.now())
        linkedManage.sendRestLinkPackage()
        break;
      case 14:
        //工作模式查询
        this.queryWorkModel(1);
        break;
      case 7:
        //打开缓冲区
        this.openBuffer()
        break;
      case 8:
        //擦除缓冲区
        this.clearBuffer()
        break;
      case 9:
        //下发文件
        this.showSendFileDialog()
        break;
      case 10:
        //关闭缓冲区
        this.closeBuffer()
        break;
      case 11:
        //下发参数
        this.doDownLoadCommand()
        break;
      case 12:
        //开始执行
        this.execute();
        break;
      case 13:
        //链路重置
        this.startLinkConnected();
        break;
    }
  },
  //打开缓冲区
  openBuffer: function () {
    let workModel = application.openBuffer(this.data.project_data_size);
    this.sendAppCommSendDate(workModel);
    console.log("发送打开缓冲区指令")
    this.show_log("打开缓冲区指令的下发")
  },
  //关闭缓冲区
  closeBuffer: function () {
    let workModel = application.closeBuffer(this.data.project_data_size);
    this.sendAppCommSendDate(workModel);
    this.show_log("关闭缓冲区指令的下发")
  },
  //擦除缓冲区
  clearBuffer: function () {
    let workModel = application.eraseBuffer(1);
    this.sendAppCommSendDate(workModel);
    this.show_log("擦除缓冲区指令的下发")
  },
  //发送文件程序提示
  showSendFileDialog: function name(params) {
    if (this.data.project_data.length < 1) {
      wx.showToast({
        title: '请先选择文件',
      })
      return
    }
    let that = this
    wx.showModal({
      title: "提示",
      content: "更新程序操作，是否继续?",
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#000000",
      confirmText: "更新",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {
          that.data.sendFileOffset = 0;
          that.setData({
            isShowSendFileProgress: true,
            sendFilePecenter: 1,
            isNeedClearBuffer: false
          })
          if (that.data.workModel == 0) {
            //需要切换到工作模式
            that.queryWorkModel(2)
            utils.sleepTime(1000)
            linkedManage.sendRestLinkPackage()
          } else {
            that.openBuffer()
          }
        }
      },
      fail: () => {

      },
      complete: () => {}
    });
  },
  //下发文件
  sendFileData: function () {
    let sendData;
    let that = this
    console.log("send file offset", this.data.sendFileOffset, "file length", this.data.project_data.length)
    let haveSendLength = this.data.project_data.length - this.data.sendFileOffset
    that.setData({
      lastLength: haveSendLength
    })
    if ((this.data.sendFileOffset + sendFileSize) <= this.data.project_data.length) {
      sendData = this.data.project_data.slice(this.data.sendFileOffset, this.data.sendFileOffset + sendFileSize)
    } else {
      let lastLength = this.data.project_data.length - this.data.sendFileOffset
      console.log("last length:", lastLength)
      if (lastLength > 0) {
        sendData = this.data.project_data.slice(this.data.sendFileOffset, this.data.sendFileOffset + lastLength)
        that.setData({
          lastLength: "end:" + this.data.sendFileOffset
        })
      } else {
        console.log("文件发送完成")
        that.show_log("文件发送完成")
        that.closeBuffer()
        this.setData({
          sendFilePecenter: 100,
          isShowSendFileProgress: false,
          isNeedSendParame:true
        })
        return
      }
    }
    sendData = utils.HexStrToByte(sendData)
    let realDate = application.sendFileData(sendData, this.data.sendFileOffset / 2)
    this.sendAppCommSendDate(realDate);
    this.data.sendFileOffset = this.data.sendFileOffset + sendFileSize
    let percenter = Math.floor((this.data.sendFileOffset / this.data.project_data.length) * 100)
    percenter = percenter > 0 ? percenter : 1
    this.setData({
      sendFilePecenter: percenter
    })

  },
  //开始执行
  execute: function () {
    let header60 = Array(60).fill(0xFF)
    header60 = utils.byteArrayToHex(header60)
    if (this.data.project_data.length > 120) {
      header60 = this.data.project_data.slice(0, 120)
    }
    let workModel = application.execute(header60);
    this.sendAppCommSendDate(workModel);
  },
  //下发参数通用
  doDownLoadCommand: function (preOperator) {
    this.changeBandActionProgress(0,'准备中')
    this.showBandErrorLog("");
    this.controlBandDialog(true)
    let readConfigDataUpdateProject = application.readConfig(this.data.picker_01_index, preOperator)
    this.sendAppCommSendDate(readConfigDataUpdateProject);
  },

  //************************************************定时器操作******************************************************
  //start train Timer @param time long second
  startTrainTimer: function (secondes) {
    var that = this;
    var beginTimeStr = that.formatTime(secondes);
    if (trainTimer) {
      trainTimer.stop();
    }
    trainTimer = new Timer({
      name: trainTimerName,
      beginTime: beginTimeStr,
      intervalUnit: 20,
      complete: function () {
        console.log("timer complete");
      },
      interval: 1,
      intervalFn: function () {
        trainLastTime = trainLastTime + 1;
        linkedManage.sendBlueTimer(that.data.supportMtu);
      }
    });
    trainTimer.start(this);
  },
  //stop train Timer
  stopTrainTimer: function () {
    if (trainTimer) {
      trainTimer.stop();
    }
  },
  //秒数--》时 分 秒
  formatTime: function (seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt((seconds / 60) % 60),
        parseInt(seconds % 60) //秒
      ]
      .join(":")
      .replace(/\b(\d)\b/g, "0$1");
  },

  handlePauseState: function () {
    var that = this;
    that.setData({
      emsWorkStatusName: "继续",
      emsWorkStatus: {
        isStop: false,
        isCountinue: false,
        isPause: true
      }
    });
  },

  /**
   * 处理应用层返回解析结果
   * */
  handleAppResult: function (result) {
    let that = this
    if (!result || result.length < 1) {
      return
    }
    switch (result[0]) {
      case application.AppPortList.properties[1].value[3].value:
        //下发参数操作返回
        if(result[1][0]!=1){
            that.showErrorDialog(application.AppErrorCode.properties[result[1][5]])
            that.controlBandDialog(false)
        }else{
           that.execute()
        }
        break;
        case application.AppPortList.properties[1].value[4].value:
          //开始运行返回
          if(result[1][0]!=1){
              that.controlBandDialog(false)
              let msg=application.AppErrorCode.properties[result[1][0]].name;
              that.show_band_log(msg)
              that.showErrorDialog(msg)
          }
          break;  
      case application.AppPortList.properties[1].value[5].value:
        //中断操作返回
        if(result[1][0]!=1){
            that.showErrorDialog(application.AppErrorCode.properties[result[1][5]])
        }
        that.controlBandDialog(false)
        break;
      case application.AppPortList.properties[1].value[6].value:
        //缓冲区打开后处理 更新framwork需要擦除缓冲区 更新程序不需要擦除
        that.show_log("缓冲区打开应答报文")
        if (that.data.isShowSendFileProgress) {
          if (that.data.isNeedClearBuffer) {
            that.clearBuffer()
          } else {
            that.sendFileData()
          }
        }else if(that.data.isNeedSendParame){
          that.doDownLoadCommand(that.data.curretSelectMenu);
        }
        break;
      case application.AppPortList.properties[1].value[7].value:
        //缓冲区 擦除后操作 发送文件
        that.show_log("缓冲区擦除应答报文")
        if (that.data.isShowSendFileProgress) {
          that.sendFileData()
        }
        break;
      case application.AppPortList.properties[0xFF].value[8].value:
        //程序更新完成
        that.show_log("收到程序更新完成")
        console.log("收到程序更新完成")
        break;
      case application.AppPortList.properties[application.AppPortList.portAscii].value:
        //自定义ascii 返回
        that.show_log("端口号" + "命令" + "自定义ascii 返回" + utils.byteArrayToHex(result[1]))
        break;
      case application.AppPortList.properties[application.AppPortList.portCustomer].value:
        //自定义消息体 返回
        if (result[1][0] == 0xFF) {
          that.handleInnerFFmsg(result[1])
        } else {
          that.handleSendFileResult(result[1])
        }
        break;
      case application.AppPortList.properties[0].value[1].value:
        //切换工作模式模式到工作模式
        console.log("查询工作模式返回")
        that.show_log("查询工作模式返回" + util.byteArrayToHex(result[1]))
        if (result[1][0] == 1) {
          that.setData({
            workModel: result[1][1]
          })
         if(that.data.workModel === 2&&that.data.isNeedSendParame){
            that.doDownLoadCommand(that.data.curretSelectMenu);
          }
          console.log("工作模式", that.data.workModel)
          let modelName = that.data.workModel === 0 ? "Boot模式" : "工作模式"
          that.show_band_log("查询工作模式返回:" + modelName)
          let checkboxDisable=that.data.workModel === 0 ? false : true
          that.switchCheckItemStatus(checkboxDisable)
        }
        if (that.data.workModel == 2 && that.data.isShowSendFileProgress) {
          console.log("查询工作模式后，更新程序操作")
          that.openBuffer();
        }
        break;
      case application.AppPortList.properties[0].value[2].value:
        //切换工作模式模式到工作模式
        console.log("切换工作模式返回")
        let result_stat = result[1][0];
        if (result_stat != 1) {
          //异常处理提醒
          let errorMsg = application.AppErrorCode.properties[result_stat].name
          that.showErrorDialog(errorMsg);
          that.setData({
            isShowSendFileProgress: false
          })
          return;
        }
        break;
      default:
        break;
    }
  },
  //处理发送文件后结果
  handleSendFileResult: function (sendFileResult) {
    let that = this
    let sourcePort = sendFileResult[0] //源端口号
    let sourceCmd = sendFileResult[1] //源命令
    console.log("源端口号:", sourcePort, " 源命令:", sourceCmd)
    // todo
    //  let portCmd = application.AppPortList.properties[sourcePort].value[sourceCmd].value
    let portCmd = application.AppPortList.properties[2].value[0].value
    switch (portCmd) {
      case application.AppPortList.properties[2].value[0].value:
        //更新程序文件
        that.sendFileData()
        break;
      case application.AppPortList.properties[2].value[1].value:
        //更新配置文件
        that.sendFileData()
        break;
      default:
        that.sendFileData()
        break;
    }

  },
  //************************************************链路层 定时器操作******************************************************
  //start train Timer @param time long second
  startLinkTimer: function (secondes) {
    var that = this;
    var beginTimeStr = that.formatTime(secondes);
    if (linkTimer) {
      linkTimer.stop();
    }
    console.log("link time ", linkedManage.linkRto * 30)
    linkTimer = new Timer({
      name: linkTimerName,
      beginTime: beginTimeStr,
      intervalUnit: linkedManage.linkRto * 30,
      complete: function () {
        console.log("linkTimer complete");
      },
      interval: 1,
      intervalFn: function () {
        linkLastTime = linkLastTime + 1;
        linkedManage.linkdoLinktimer();
      }
    });
    linkTimer.start(this);
  },
  //stop link Timer
  stopLinkTimer: function () {
    if (linkTimer) {
      linkTimer.stop();
    }
  },
  //更新程序操作
  touchEndUpdate: function () {

  },
  //切换默认设置
  switchMaintain: function (e) {
    if (e.type != "change") {
      return;
    }
    if (e.detail.value) {
      this.setData({
        isHideMaintain: false
      })
    } else {
      this.setData({
        isHideMaintain: true
      })
    }
  },
  //更新
  touchFirmwork: function (e) {
    let that = this
    if (that.data.workModel != 0) {
      wx.showModal({
        title: "提示",
        content: "当前操作需要拔插设备!",
        showCancel: false,
        cancelText: "取消",
        cancelColor: "#000000",
        confirmText: "确定",
        confirmColor: app.globalData.buttonStyleColor,
        success: result => {},
        fail: () => {},
        complete: () => {}
      });
      return
    }
    wx.showModal({
      title: "提示",
      content: "更新FramWork操作，是否继续?",
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#000000",
      confirmText: "更新",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {
          this.selectFile(e, function selectResult(param) {
            //文件选择成功后 切换到boot模式
            that.openBuffer()
            that.setData({
              isShowSendFileProgress: true,
              sendFilePecenter: 1,
              isNeedClearBuffer: true,
            })
          });
        }
      },
      fail: () => {

      },
      complete: () => {}
    });

  },
  touchStartFramWork: function () {
    var that = this;
    that.setData({
      isClickFrameWork: true
    });
  },
  touchEndFrameWork: function (e) {
    var that = this;
    that.setData({
      isClickFrameWork: false
    });
    this.touchFirmwork(e);
  },
  sliderMTUchange: function (e) {
    let configMtu = e.detail.value*20;
    this.configBlueMtu(configMtu);
  },
  setBlueMtu:function(configMtu){
    let that=this
    try {
      wx.setBLEMTU({
        deviceId: that.data.deviceId,
        mtu: configMtu+3,
        success: (res) => {
          console.log('setBLEMTU:success:', res)
          wx.showToast({
            title: 'mtu配置成功',
          })
          //设置支持的最大mtu
          let slideSupportMtu=parseInt(configMtu/20)
         that.setData({
            supportMtu:configMtu ,
            slideSupportMtu:slideSupportMtu
         })
         that.configBlueMtu(configMtu);
         let tmpMtu=configMtu+20;
         that.setBlueMtu(tmpMtu)
        },
        fail(res) {
          console.error('setBLEMTU:fail:', res)
        },
        complete(res){
          console.error('setBLEMTU:complete:', res)

        }
      })
     
    } catch (error) {
      wx.showToast({
        title: 'mtu配置异常',
      })
    }
  },
  sliderActionIntervalchange:function(e){
    let plusPause = e.detail.value;
    let sleepPlusPause=parseFloat(plusPause*0.001).toFixed(1)
    this.setData({
      intervalValueShow: sleepPlusPause,
      intervalValue:plusPause
    });
    console.log(`当前值 intervalValue`, this.data.intervalValue);
  },
  //错误弹框
  showErrorDialog: function (errorMsg) {
    wx.showModal({
      title: "提示",
      content: errorMsg,
      showCancel: false,
      cancelText: "取消",
      cancelColor: "#000000",
      confirmText: "确定",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {

        }
      },
      fail: () => {

      },
      complete: () => {}
    });
  },
  //处理自定义消息 源端口为FF的
  handleInnerFFmsg: function (contentData) {
    let that = this
    let sourcePort = contentData[0];
    let cmdSeq = contentData[1];
    let seq = contentData[2];
    let ackType = contentData[3];
    let ackDataLength = contentData[4]
    let msgData = contentData.slice(5, ackDataLength + 5)
    let msgType = msgData[0]; //消息类型
    let msgSource = msgData[1] //消息来源
    if (msgSource == application.AppblueMsgSource.blue) {
      console.log("过滤蓝牙信息")
      return;
    }
    let msg = "板子操作" + application.AppblueMsgType.properties[msgType].name;
    let msgBytes = msgData.slice(2, msgData.length)
    let msgHexStr = utils.byteArrayToHex(msgBytes)
    let msgStr = utils.hexCharCodeToStr(msgHexStr)
    if(msgType==application.AppblueMsgType.progress){
      that.changeBandActionProgress(msgStr,'执行中')
    }else if(msgType==application.AppblueMsgType.info){
      let bandmsg=msg + ":" + that.getHtmlUsefulText(msgStr)
      that.show_band_log(bandmsg)
    }else{
      that.show_band_log(msgStr)
    }
    if(msgType==application.AppblueMsgType.sucess||msgType==application.AppblueMsgType.error){
        if (that.checkIsContinueExecute()){
            utils.sleepTime(that.data.intervalValue)
            that.doDownLoadCommand(that.data.curretSelectMenu);
            let count=that.data.calc_count+1;
            that.changeCalcuCount(count)
        }else {
          that.controlBandDialog(false)
          that.showErrorDialog(application.AppblueMsgType.properties[msgType]);
        }
        if(msgType==application.AppblueMsgType.error){
          that.showBandErrorLog(msgStr);
          that.playFailMp3()
        }
    }
  },
  /**
   * 切换工作模式报文
   */
  switchWorkModel:function(){
    this.queryWorkModel(2)
    utils.sleepTime(2000)
    linkedManage.sendRestLinkPackage()
  },
  /**
   * 是否继续执行
   */
  checkIsContinueExecute:function (){
    let selectItems=this.data.items;
    let tmp=false;
    for (let i = 0; i < selectItems.length; i++) {
        if (selectItems[i].operatorValue===0&&selectItems[i].checked){
          tmp=true;
          break;
        }
    }
    return tmp;
  },
  /**
   * 
   * @param {是否可以联系执行} enble 
   */
  configContinueExecute:function (enble){
    let selectItems=this.data.items;
    for (let i = 0; i < selectItems.length; i++) {
        if (selectItems[i].operatorValue===0){
          selectItems[i].checked=enble
          break;
        }
    }
    this.setData({
      items:selectItems
    })
  },
  /**
   * 改变进度条的数值
   * @param progress
   */
  changeBandActionProgress:function (progress,status){
    if(progress==0){
      status="准备中"
      this.data.isExcuting=true;
      this.show_band_log(status)
    }else if(this.data.isExcuting){
      this.data.isExcuting=false;
      status="执行中"
      this.show_band_log(status)
    }else if(progress>=100){
      status="成功"
      this.show_band_log(status)
      this.playSuccessMp3()
    }
    console.log("progress:",progress)
    this.setData({
      bandActionProgress:progress,
      bandStatus:status,
    })
  },
  /**
   * 是否显示板卡信息弹框
   * @param visual
   */
  controlBandDialog:function (visual){
    this.setData({
      isShowBandActionDialog:visual
    })
  },
  stopExecute:function(e){
    let that=this
    wx.showModal({
      title: "提示",
      content: "是否终止执行?",
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#000000",
      confirmText: "确定",
      confirmColor: app.globalData.buttonStyleColor,
      success: result => {
        if (result.confirm) {
         that.stopBandExcute()
        }
      },
      fail: () => {

      },
      complete: () => {}
    });
  },
    //终止板卡操作
    stopBandExcute: function () {
      console.log("终止板卡操作")
      let workModel = application.doStopBandExecute();
      console.log("终止板卡操作 报文" + utils.byteArrayToHex(workModel))
      let workModelData = linkedManage.sendApplicationData(0, workModel)
      linkedManage.sendBlueData(workModelData)
      this.show_band_log("终止板卡报文发送")
      this.setData({
        isNeedSendParame:false
      })
      this.configContinueExecute(false)
    },
    /**
     * checkbox 的状态改变
     * @param {是否} disable 
     */
    switchCheckItemStatus:function(disable){
      // let selectItems=this.data.items;
      // for (let i = 0; i < selectItems.length; i++) {
      //      selectItems[i].disable=disable
      // }
      // this.setData({
      //   items:selectItems
      // })
    },
    /**
     * 
     * @param {板子的错误信息} log 
     */
    showBandErrorLog:function(log){
      this.setData({
        bandStatusError:log
      })
    },

    configBlueMtu:function(mtu){
      let that=this
      let slideMtu=parseInt(mtu/20)
      that.setData({
        mtuValue: slideMtu
      });
      blue.configMTU(mtu)
      console.log("MTU:" + mtu)
      that.show_log("MTU大小：" + mtu)
      that.saveMtu(mtu);
    },
    saveMtu: function (defaultMtu) {
      wx.setStorage({
        key: "defaultMtu",
        data: defaultMtu,
        success: result => { },
        fail: () => { },
        complete: () => { }
      });
    },
    queryMtu:function(){
      let that=this;
      wx.getStorage({
        key: 'defaultMtu',
        success (res) {
         that.setBlueMtu(res.data)
        },
        fail: () => {
          that.setBlueMtu(20)
         },
      })
    },
    playSuccessMp3:function(){
      console.log("开始播放success")
      innerAudioContext.src = '/images/success.mp3'
      innerAudioContext.play() // 播放
    },
    playFailMp3:function(){
      console.log("开始播放fail")
      innerAudioContext.src = '/images/fail.mp3'
      innerAudioContext.play() // 播放
    },
    /**
     * 获取html 正常显示的文本
     */
    getHtmlUsefulText:function(str){
     let html= '<div style="color: blue;">'+str+'</div>'
     return html;
    },
    /**
     * 程序计数器
     * @param {个数} num 
     */
    changeCalcuCount:function(num){
      this.setData({
        calc_count:num
      })
    }
})